import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import {
  addArticleInfo,
  deleteArticleById,
  getArticleDetailById,
  getArticleList,
  modifyArticleInfo,
} from "../../service/modules/article";

interface articleState {
  total: number;
  articleList: any[];
  articleDetail: any;
}
const initialState: articleState = {
  total: 0,
  articleList: [],
  articleDetail: {},
};
/**
 * @获取列表
 */
export const fetchGetArticleListAction = createAsyncThunk(
  "article/list",
  async (query: { pageSize: number; pageNum: number }) => {
    const res = await getArticleList(query);
    // console.log(res);

    return res;
  }
);
/**
 * @详情
 */
export const fetchGetDetailInfoAction = createAsyncThunk(
  "article/detail",
  async (id: number) => {
    const res = await getArticleDetailById(id);
    // console.log(res);
    return res.data;
  }
);
/**
 * @新增
 */
export const fetchAddArticleAction = createAsyncThunk(
  "article/add",
  async (body: {
    content: string | null;
    createBy: string | null;
    createTime: null;
    id: null | number;
    image: null | string;
    likes: null | number;
    state: string;
    sysDeptId: number | null;
    sysUserId: null;
    title: string;
    updateBy: null | string;
    updateTime: null | string;
  }) => {
    const res = await addArticleInfo(body);
    // console.log(res);
    return res;
  }
);

export const fetchUpdateArticleAction = createAsyncThunk(
  "article/update",
  async (body: {
    comments: number;
    content: string | null;
    createBy: string | null;
    createTime: string | null;
    id: number | null;
    image: string | null;
    likes: number | null;
    remark: string | null;
    state: string;
    sysDeptId: number | null;
    title: string;
    updateBy: string | null;
    updateTime: string | null;
    userId: number;
  }) => {
    const res = await modifyArticleInfo(body);
    // console.log(res);
    return res;
  }
);

/**
 * @删除
 */
export const fetchDeleteArticleAction = createAsyncThunk(
  "article/delete",
  async (ids: string[]) => {
    const res = await deleteArticleById(ids);
    // console.log(res);
    return res;
  }
);
const articleSlice = createSlice({
  name: "article",
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(fetchGetArticleListAction.fulfilled, (state, action) => {
        state.articleList = action.payload.rows;
        state.total = action.payload.total;
      })
      .addCase(fetchGetDetailInfoAction.fulfilled, (state, action) => {
        state.articleDetail = action.payload;
      });
  },
});

export default articleSlice.reducer;
